// sUndefined = require('lodash/isUndefined')
const isNumber = require('lodash/isNumber')
const cloud = require('wx-server-sdk')
const appid = process.env.appid //你的小程序appid
const secret = process.env.secretkey //你的小程序secret

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const ERROR_MSG = {
    500: '服务器错误',
    401: '登录过期',
    404: '未找到资源',
    4001: '重复提交'
}
class CustomError extends Error {
    constructor(code, msg) {
        super()
        this.code = code || 500
        this.msg = msg || ERROR_MSG[code] || 'unknown error'
    }
    getCodeMsg() {
        return {
            code: this.code,
            msg: this.msg
        }
    }
}
// 增加额外command功能
const _ = db.command
// 1. 获取数据库引用
const TcbRouter = require('tcb-router')
const { get } = require('request')

exports.main = async (event, context) => {
    const app = new TcbRouter({ event })
    const { OPENID, UNIONID } = cloud.getWXContext()
    const {
        comments_id
    } = event
    app.use(async (ctx, next) => {
        //适用于所有的路由
        ctx.data = {} //声明data为一个对象
        try {
            ctx.body = {}
            ctx.body.code = 0
            await next()
        } catch (err) {
            console.log(err, 'err'.repeat(10))
            console.log(ctx)
            if (err instanceof CustomError) {
                const res = err.getCodeMsg()
                ctx.body = {}
                ctx.body.code = res.code || 500
                ctx.body.msg = res.msg
            } else if (err instanceof Error) {
                console.log(err)
                ctx.body = {}
                ctx.body.code = 500
                ctx.body.msg = err.message
            } else if (typeof err === 'string') {
                ctx.body = {}
                ctx.body.code = 500
                ctx.body.msg = err
            } else {
                ctx.body = {}
                ctx.body.code = res.code || 500
                ctx.body.msg = res.msg
            }
        }
    })
    //查找数据库中的所有数据
    app.router("findAll", async (ctx, next) => {
        try {
            // 1，获取数据的总个数
            let count = await db.collection('forum_data').count()
            count = count.total
            // 2，通过for循环做多次请求，并把多次请求的数据放到一个数组里
            let all = []
            for (let i = 0; i < count; i += 100) { //自己设置每次获取数据的量
                let list = await db.collection('forum_data').skip(i).get()
                all = all.concat(list.data);
            }
            // 3,把组装好的数据一次性全部返回
            return ctx.body = {
                all
            }

        } catch (error) {
            return ctx.body = {
                error
            }
        }
    })
    //论坛的添加
    app.router('addForum', async (ctx, next) => {
        const {
            userTitle,
            userContent,
            url,
            author,
            author_url,
            content_time,
            date

        } = event.data[0]
        try {
            await db.collection("forum_data").add({
                data: {
                    forum_id: event.userInfo.openId,
                    author: author,
                    author_url: author_url,
                    title: userTitle,
                    contents: userContent,
                    picture: url,
                    tv: null,
                    content_time: content_time,
                    date: date,
                    // content_id: "id_" + res.data.length moment().format('YYYY-MM-DD:HH:MM:SS')
                }
            }).then(res => {
                return ctx.body = {
                    res
                }
            })
        } catch (error) {
            return ctx.body = {
                error
            }
        }

    })
    // 查询当天发布的论坛
    app.router("commentsToday", async (ctx, next) => {
        const { date } = event
        const { openId } = event.userInfo
        try {
            await db.collection("forum_data").where({
                // 条件
                date: date
            }).get().then(res => {
                return ctx.body = {
                    res
                }
            })
        } catch (error) {
            return ctx.body = {
                error
            }
        }
    })

    //删除论坛的论述时同时也会把论述中的评论删除
    app.router("del_Forum", async (ctx, next) => {
        try {
            await db.collection("forum_data").where({
                comments_id: comments_id
            }).remove().then(res => {
                // const id = "id_" + comments_id
                db.collection("comments").where({
                    content_id: res.data[0].content_id
                }).remove().then(() => {
                    console.log("删除成功")
                })
            })
        } catch (error) {
            return ctx.body = {
                error
            }
        }

    })

    //每个论坛的评论数的添加
    app.router("Comment", async (ctx, next) => {
        const {
            forum_title,
            person_name,
            comments_url,
            comments_contents,
            content_id,
            comments_time,
            cmt_id
        } = event.data
        // return event
        try {//从论坛表里找出对应的论坛（）并加入相对应的评论
            await db.collection("comments").add({
                data: {
                    forum_title: forum_title,
                    person_name: person_name,
                    comments_url: comments_url,
                    comments_contents: comments_contents,
                    content_id: content_id,
                    comments_time: comments_time,
                    cmt_id: cmt_id,
                    like:false,
                    love_people:null,
                }
            }).then(res => {
                return ctx.body = {
                    res
                }
            })

        } catch (error) {
            return ctx.body = {
                error
            }
        }
    })
    // 评论的删除
    app.router("del_comments", async (ctx, next) => {
        //通过_id获取到具体删除那条评论
        const { _id } = event
        try {
            await db.collection("comments").where({
                _id: _id
            }).remove().then(res => {
                return ctx.body = {
                    res
                }
            })
            // await db.collection("forum").where({
            //     comments_id: comments_id
            // }).get().then(res => {
            //     const { content_id } = res.data
            //     db.collection("comments").where({
            //         content_id: content_id
            //     }).remove().then(res => {

            //         console.log("评论删除成功")
            //     })
            // })
        } catch (error) {
            return ctx.body = {
                error
            }
        }
    })
    //用户帖子以及对应评论的展示
    app.router("inf", async (ctx, next) => {
        try {
            await db.collection("forum_data").where({
                forum_id: event.userInfo.openId
            }).get().then(res => {
                return ctx.body = {
                    res
                }
                const { content_id } = res.data
                db.collection("comments").where({
                    content_id: content_id
                }).get().then(res => {
                    return ctx.body = {
                        res
                    }
                })

            })
        } catch (error) {
            return ctx.body = {
                error
            }
        }
    })
    //查看每个发布的帖子的评论
    app.router("find_Comments", async (ctx, nexr) => {
        const { openid, title } = event
        // return ctx.body={
        //     openid,title
        // }
        try {//根据评论人的
            await db.collection("comments").where({
                cmt_id: openid,
                forum_title: title
            }).get().then(res => {
                return ctx.body = {
                    res
                }
            })
        } catch (error) {
            return ctx.body = {
                error
            }
        }
    })
    // 查看个人发帖情况
    app.router("find_one", async (ctx, next) => {
        try {
            await db.collection("forum_data").where({
                forum_id: event.userInfo.openId
            }).get().then(res => {
                return ctx.body = {
                    res
                }
            })
        } catch (error) {
            return ctx.body = {
                error
            }
        }
    })
    //增加收藏
    app.router("addLike", async (ctx, next) => {
        const { _id,person_name,  } = event.newData

        try {//先找到那条评论
            await db.collection("comments").where({
                _id
            }).update({
                data: {
                    like: true,
                    love_people: [{name:person_name}]
                }
            }).then((res) => {
                return ctx.body = {
                    res
                }
            })
        } catch (error) {
            return ctx.body = {
                error
            }
        }
    })
    // 取消收藏
    app.router("delLike", async (ctx, next) => {
        const { _id, person_name, } = event.newData
        try {//先找到那条评论
            await db.collection("comments").where({
                _id
            }).update({
                data: {
                    love_people: _.pop({name:person_name})
                }
            }).then((res) => {
                return ctx.body = {
                   res
                }
            })
        } catch (error) {
            return ctx.body = {
                error
            }
        }
    })
    return app.serve()
}
